package com.study.util;

import java.sql.*;
import java.util.Properties;

/**
 * @PackgeName: com.study.util
 * @ClassName: JdbcUtil
 * @Author: 严志祥
 * Date: 2022-05-04 15:46
 * project name: web_project_medal
 * @Version:
 * @Description:
 */
public class JdbcUtil {
private static String driver;
private static String url;
private static String username;
private static String password;

static{
try{
Properties config = new Properties();
config.load(JdbcUtil.class.getResourceAsStream("/jdbc.properties"));
Class.forName(config.getProperty("jdbc.driverClassName","com.mysql.jdbc.Driver"));
url =config.getProperty("jdbc.url");
username = config.getProperty("jdbc.username");
password = config.getProperty("jdbc.password");
}catch (Exception e){
    e.printStackTrace();
}
}

    /**
     *
     * @return
     */
    public static Connection getConn(){
Connection conn = null;
try{
    conn = DriverManager.getConnection(url,username,password);
}catch (Exception e){
    e.printStackTrace();
}
return conn;
}

    /**
     *
     * @param conn
     * @param pst
     * @param rs
     */
    public static void closeAll(Connection conn, PreparedStatement pst, ResultSet rs){
if(rs != null){
try{
    rs.close();
}catch (Exception e){
    e.printStackTrace();
}
}
    if(pst != null){
        try{
            pst.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    if(conn != null){
        try{
            conn.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
    /**
     * 设置预处理的语句对象的参数
     * @param pstmt
     * @param objs
     * @throws SQLException
     */
    public static void setParam(PreparedStatement pstmt,Object ... objs) throws SQLException {
        if(objs==null || objs.length==0){
            return;
        }
        for (int i = 0; i < objs.length; i++) {
            pstmt.setObject(i+1,objs[i]);
        }
    }

    /**
     * 封装jdbc语句的执行（insert,update,delete）
     * @param sql
     * @param objs
     * @return
     * @throws SQLException
     */
    public static int execute(String sql,Object...objs) throws SQLException {
        try(
                Connection conn = getConn();
                PreparedStatement pstmt = conn.prepareStatement(sql);
        ) {
            setParam(pstmt,objs);
            return pstmt.executeUpdate();
        }
    }

    /**
     *
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(JdbcUtil.getConn());
    }
}
